package vcf导出为excel;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ReadVcardToExcel {

	
	public static Map<String, String> UserToExcel(String vpath,String epath){
		
		Map<String, String> map = null;
		
		try {
			String[] tmp = readVcard(vpath);
			map = extractingNameAndPhone(tmp);
			writeExcel(map, epath);
		} catch (UnsupportedEncodingException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return map;
		
	}
	public static void main(String[] args) {
		String newFile = "E://test.xls";

		try {
			String[] tmp = readVcard("E://00001.vcf");
			Map<String, String> map = extractingNameAndPhone(tmp);

//			createFile("E://", "test.xls");

			writeExcel(map, newFile);
		} catch (UnsupportedEncodingException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

	}

	/**
	 * 读取vcard，返回切割后的个人信息
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 */
	private static String[] readVcard(String path) throws IOException {

		File vFile = new File(path);

		StringBuffer sb = new StringBuffer();

		BufferedReader br = new BufferedReader(new InputStreamReader(
				new FileInputStream(vFile)));

		String tmp = "";
		while ((tmp = br.readLine()) != null) {
			sb.append(tmp);
		}

		String[] np = sb.toString().split("ND:VCARD");

		return np;

	}

	/**
	 * extraction :提取，抽取
	 * 
	 * @throws UnsupportedEncodingException
	 * 
	 */
	private static Map<String, String> extractingNameAndPhone(String[] np)
			throws UnsupportedEncodingException {

		Map<String, String> map = new HashMap<String, String>();

//		System.out.println("总联系人数："+np.length);
		for (String s : np) {
			int nbg = s.indexOf("FN:");
			int nend = s.indexOf("TEL;", nbg);
			String name = null;

			if (nbg != -1 && nend != -1) {
//				System.out.println("nbg:" + nbg + " nend:" + nend);
				name = s.substring(nbg + 3, nend);

				if (name.contains("=")) {
					name = URLDecoder.decode(name.replace('=', '%'), "UTF-8");
				}

			} else {
				name = "无姓名";
			}
//			System.out.println("name :" + name);

			int pbg = s.indexOf("TEL;TYPE=CELL:");
			int pend = -1;
			String phone = null;

			String temp = s.substring(pbg + 14);

			if (temp.contains("-")) {
				temp = temp.replace("-", "");
			}
//			System.out.println("temp : " + temp);
			for (int i = 2; i < temp.length(); i++) {
				if (!Character.isDigit(temp.charAt(i))) {
					pend = i;
					break;
				}
			}
//			System.out.println("pbg:" + pbg + " pend:" + pend);

			if (pbg != -1 && pend != -1) {
				phone = temp.substring(0, pend);
			} else {
				phone = "无联系方式";
			}
//			System.out.println("phone :" + phone);

			map.put(name, phone);
		}

		return map;
	}

	private static void writeExcel(Map<String, String> map, String fpath) {


		String[] title = { "姓名", "联系方式" };

		HSSFWorkbook workbook = new HSSFWorkbook();

		HSSFSheet sheet = workbook.createSheet();
		HSSFRow row = sheet.createRow(0);

		HSSFCell titleCell = null;

		// 插入第一行数据
		for (int i = 0; i < title.length; i++) {
			titleCell = row.createCell(i);
			titleCell.setCellValue(title[i]);
		}

		// 追加数据

		Object[] names = map.keySet().toArray();

//		for(Object o:names){
//			System.out.println(o);
//		}
		System.out.println("names.length："+names.length);
		for (int i = 0; i < names.length; i++) {
			HSSFRow nextRow = sheet.createRow(i+1);
			HSSFCell cell = nextRow.createCell(0);
			cell.setCellValue(names[i] + "");
			cell = nextRow.createCell(1);
			cell.setCellValue(map.get(names[i]));
			System.out.println(i+" "+names[i]+" : "+map.get(names[i]));
		}
		
		
		try {
			File excel = new File(fpath);
			excel.createNewFile();
			FileOutputStream fout = FileUtils.openOutputStream(excel);
			workbook.write(fout);
			fout.close();
			workbook.close();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

}
